package com.yue92.datalife.filter;

import com.yue92.datalife.common.CodeEnum;
import com.yue92.datalife.common.Constant;
import com.yue92.datalife.exception.UncheckedException;
import com.yue92.datalife.model.User;
import com.yue92.datalife.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Optional;

@Component
public class ClientAuthorizationFilter extends AbstractAuthorizationFilter {

    @Autowired
    private IUserService userService;

    @Override
    protected UsernamePasswordAuthenticationToken authenticate(HttpServletRequest request) {
        String authorization = request.getHeader(AUTHORIZATION_HEADER);
        if (!StringUtils.isEmpty(authorization)) {
            Optional<User> userOptional = userService.getByToken(authorization);
            if (userOptional.isPresent()) {
                User user = userOptional.get();

                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        user,
                        null,
                        new ArrayList<>());
                request.setAttribute(Constant.CURRENT_USER_ATTRIBUTE, user);
                return authentication;
            } else {
                request.setAttribute(Constant.EXCEPTION_ATTRIBUTE, new UncheckedException(CodeEnum.LOGIN_TOKEN_INVALID));
            }
        } else {
            request.setAttribute(Constant.EXCEPTION_ATTRIBUTE, new UncheckedException(CodeEnum.LOGIN_TOKEN_INVALID));
        }

        return null;
    }
}